import React, { Component } from "react";
import { citys } from "./util/city";
import Core from "./util/core";
var overlays = [];
var style = [
  {
    url: "https://a.amap.com/jsapi_demos/static/images/mass0.png",
    anchor: new AMap.Pixel(6, 6),
    size: new AMap.Size(11, 11)
  },
  {
    url: "https://a.amap.com/jsapi_demos/static/images/mass1.png",
    anchor: new AMap.Pixel(4, 4),
    size: new AMap.Size(7, 7)
  },
  {
    url: "https://a.amap.com/jsapi_demos/static/images/mass2.png",
    anchor: new AMap.Pixel(3, 3),
    size: new AMap.Size(5, 5)
  }
];
class WebMap extends Component {
  constructor(props) {
    super(props);
    this.state = {
      map: null,
      massMarks: null,
      mouseTool: null,
      district: null,
      polygons: [],
      mapID: `amap_${Core.getRandom()}`
    };
    Core.insert({
      name: "amap",
      src:
        "https://webapi.amap.com/maps?v=1.4.15&key=1550bd9a0bd1bb4cd5d30fc9a7fe44a4&plugin=AMap.MouseTool,AMap.DistrictSearch&callback=init"
    });
  }
  componentWillReceiveProps(nextProps) {
    const { map } = this.state;
    if (nextProps.showMass) {
      // 加载海量点
      const massMarks = this.initMass(map);
      this.setState({
        massMarks: massMarks
      });
    }
    if (nextProps.showMouseTool) {
      // 画图形工具
      const mouseTool = this.initDraw(map);
      this.setState({
        mouseTool: mouseTool
      });
    }
  }
  componentDidMount() {
    window.init = () => {
      if (!window.AMap) {
        console.error("amap is required");
      } else {
        const map = this.initMap();
        this.setState({
          map: map
        });
      }
    };
  }
  componentWillUnmount() {
    Core.remove("amap");
    window.AMap = null;
  }
  // 初始化地图
  initMap() {
    const { mapID } = this.state;
    const map = new AMap.Map(mapID, {
      zoom: 4,
      center: [102.342785, 35.312316],
      mapStyle: "amap://styles/light"
    });
    return map;
  }
  // 初始化海量点
  initMass(map) {
    const massMarks = new AMap.MassMarks(citys, {
      opacity: 0.8,
      zIndex: 111,
      cursor: "pointer",
      style: style
    });
    let marker = new AMap.Marker({ content: " ", map: map });
    massMarks.on("mouseover", function(e) {
      marker.setPosition(e.data.lnglat);
      marker.setLabel({ content: e.data.name });
    });
    massMarks.setMap(map);
    return massMarks;
  }
  // 准备画图形
  initDraw(map) {
    let mouseTool = new AMap.MouseTool(map);
    //监听draw事件可获取画好的覆盖物
    mouseTool.on("draw", e => {
      overlays.push(e.obj);
      //创建右键菜单
      let contextMenu = new AMap.ContextMenu();
      contextMenu.addItem("继续画", function() {}, 0);
      contextMenu.addItem(
        "关闭画笔",
        function() {
          mouseTool.close(false);
        },
        1
      );
      let lnglat;
      if (e.obj.CLASS_NAME === "AMap.Circle") {
        lnglat = new AMap.LngLat(e.obj.B.center.lng, e.obj.B.center.lat);
      } else if (e.obj.CLASS_NAME === "AMap.Polygon") {
        lnglat = new AMap.LngLat(e.obj.B.path[0].lng, e.obj.B.path[0].lat);
      } else {
        return;
      }
      contextMenu.open(map, lnglat);
    });
    // this.drawing("rectangle", mouseTool);
    return mouseTool;
  }
  drawing(type, mouseTool) {
    mouseTool = mouseTool || this.state.mouseTool;
    switch (type) {
      case "rectangle": {
        mouseTool.rectangle({
          fillColor: "#00b0ff",
          strokeColor: "#80d8ff"
          //同Polygon的Option设置
        });
        break;
      }
      case "circle": {
        mouseTool.circle({
          fillColor: "#00b0ff",
          strokeColor: "#80d8ff"
          //同Circle的Option设置
        });
        break;
      }
    }
  }
  drawBounds(code) {
    let that = this;
    let district = this.state.district;
    let polygons = this.state.polygons;
    let map = this.state.map;
    //加载行政区划插件
    if (!this.state.district) {
      //实例化DistrictSearch
      var opts = {
        subdistrict: 0, //获取边界不需要返回下级行政区
        extensions: "all", //返回行政区边界坐标组等具体信息
        level: "district" //查询行政级别为 市
      };
      district = new AMap.DistrictSearch(opts);
      this.setState({
        district: district
      });
    }
    //行政区查询
    // district.setLevel("district");
    district.search(code, function(status, result) {
      map.remove(polygons); //清除上次结果
      polygons = [];
      var bounds = result.districtList[0].boundaries;
      if (bounds) {
        for (var i = 0, l = bounds.length; i < l; i++) {
          //生成行政区划polygon
          var polygon = new AMap.Polygon({
            strokeWeight: 1,
            path: bounds[i],
            fillOpacity: 0.4,
            fillColor: "#80d8ff",
            strokeColor: "#0091ea"
          });
          polygons.push(polygon);
        }
      }
      map.add(polygons);
      map.setFitView(polygons); //视口自适应
      that.setState({
        polygons: polygons
      });
    });
  }
  setOnMarkerHandler(item) {
    const map = this.state.map;
    let that = this;
    let marker = new AMap.Marker({
      icon: new AMap.Icon({
        imageSize: new AMap.Size(22, 30),
        image:
          "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png"
      }),
      position: [item.pos[0], item.pos[1]],
      offset: new AMap.Pixel(-11, -15)
    });
    marker.setMap(map);
    map.setFitView(marker, null, null, 6); //视口自适应
    marker.on("click", function(e) {
      marker.setLabel({ content: item.carObj.no });
      that.props.showDialog(item);
    });
  }
  closeDrawing() {
    const mouseTool = this.state.mouseTool;
    // 关闭不清除
    if (mouseTool) {
      mouseTool.close(false);
    }
  }
  closeClear() {
    const mouseTool = this.state.mouseTool;
    const polygons = this.state.polygons;
    //关闭，并清除覆盖物
    if (mouseTool) {
      mouseTool.close(true);
    }
    if (polygons.length) {
      this.state.map.remove(polygons);
    }
    // 清除不关闭
    //   map.remove(overlays);
    //   overlays = [];
  }
  render() {
    return (
      <div style={{ width: "100%", height: "100%" }}>
        <div
          id={this.state.mapID}
          style={{ width: "100%", height: "100%" }}
        ></div>
      </div>
    );
  }
}

export default WebMap;
